package com.hjq.mallproduct.service.impl;

import com.hjq.common.constants.ProductConstants;
import com.hjq.common.entity.es.SkuEsModel;
import com.hjq.common.entity.to.SkuReductionTO;
import com.hjq.common.entity.to.SpuBoundsTO;
import com.hjq.common.utils.R;
import com.hjq.mallproduct.entity.*;
import com.hjq.mallproduct.entity.vo.*;
import com.hjq.mallproduct.feign.CouponFeign;
import com.hjq.mallproduct.feign.SearchFeign;
import com.hjq.mallproduct.feign.WareFeign;
import com.hjq.mallproduct.service.*;
import com.mysql.cj.util.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjq.common.utils.PageUtils;
import com.hjq.common.utils.Query;

import com.hjq.mallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService infoDescService;
    @Autowired
    SpuImagesService imagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuAttrValueService;
    @Autowired
    CouponFeign couponFeign;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService catService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    WareFeign wareFeign;
    @Autowired
    SearchFeign searchFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVO spuInfo) {
        //保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setCreateTime(new Date());
        this.saveBaseInfo(spuInfoEntity);


        Long spuInfoEntityId = spuInfoEntity.getId();


        //保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntityId);
        String description = spuInfo.getSpuDescription();
        spuInfoDescEntity.setDecript(String.join(",",description));
        infoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //保存spude图片集 pms_spu_images
        List<String> images = spuInfo.getImages();
        imagesService.saveImages(spuInfoEntityId,images);
        //保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            attrValueEntity.setAttrName(attrEntity.getAttrName());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            attrValueEntity.setSpuId(spuInfoEntityId);
            return attrValueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttrBatch(attrValueEntities);

        //保存spu积分信息 sms_spu_bounds
        Bounds bounds = spuInfo.getBounds();
        SpuBoundsTO spuBoundsTO = new SpuBoundsTO();
        BeanUtils.copyProperties(bounds,spuBoundsTO);
        spuBoundsTO.setSpuId(spuInfoEntityId);

        R r = couponFeign.saveSpuBounds(spuBoundsTO);
        if(r.getCode()!=0){
            log.error("远程调用SpuBound积分出错");

        }

        //保存spu对应额sku:
        //1.sku基本信息：pms_sku_info
        List<Skus> skus = spuInfo.getSkus();
        if(skus!=null && skus.size()>0){


            skus.forEach(item->{
                String defaultImg = "";
                for (Images image: item.getImages()) {
                    if(image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                    }

                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntityId);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                 //sku图片信息：pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {

                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return  skuImagesEntity;
                }).filter(object-> !StringUtils.isNullOrEmpty(object.getImgUrl()))
                        .collect(Collectors.toList());

                skuImagesService.saveBatch(skuImagesEntities);

                //sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attr1 -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr1, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;

                }).collect(Collectors.toList());
                skuAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //sku的优惠满减等信息 gulimall-sms->sms_sku_ladder/sms_sku_full_reduction/sms_member_price/
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item,skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                skuReductionTO.setMemberPrice(item.getMemberPrice());
                if(skuReductionTO.getFullCount()>0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0){
                    R r1 = couponFeign.saveSkuReduction(skuReductionTO);
                    if(r1.getCode()!=0){
                        log.error("远程调用保存Sku优惠信息出错");

                    }
                }


            });

            };


    }


    @Override
    public void saveBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        String key =(String)params.get("key");
        String brandId = (String)params.get("brandId");
        String catelogId = (String)params.get("catelogId");
        String status = (String) params.get("status");



        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        if(catelogId!="0"&&!StringUtils.isEmptyOrWhitespaceOnly(catelogId)){
            spuInfoEntityQueryWrapper.eq("catalog_id",catelogId);
        }
        if(!StringUtils.isEmptyOrWhitespaceOnly(brandId)){
            spuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }
        if(!StringUtils.isEmptyOrWhitespaceOnly(status)){
            spuInfoEntityQueryWrapper.eq("publish_status",status);
        }
        if(!StringUtils.isEmptyOrWhitespaceOnly(key)){
            spuInfoEntityQueryWrapper.eq("id",key).or().like("spu_name",key).or().like("spu_description",key);

        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper

        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void upSpuInfoToES(Long spuId) {
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<>();
        //Attr信息
        List<ProductAttrValueEntity> productAttrValueList = productAttrValueService.getAttrListOfSpu(spuId);
        List<ProductAttrValueEntity> collect = productAttrValueList.stream().filter(paValue -> {
            Long attrId = paValue.getAttrId();
            return attrService.getById(attrId).getSearchType() == 1;
        }).collect(Collectors.toList());

        ArrayList<SkuEsModel.Attr> attrs = new ArrayList<>();
        if(collect.size()>0){

            collect.forEach(item->{
                SkuEsModel.Attr attr = new SkuEsModel.Attr();
                BeanUtils.copyProperties(item,attr);
                attrs.add(attr);
            });}

        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        for (SkuInfoEntity sku:skus) {
            //sku信息
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //brand信息
            Long brandId = sku.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId);
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            //catlog信息
            Long catalogId = sku.getCatalogId();
            CategoryEntity cat = catService.getById(catalogId);
            skuEsModel.setCatalogName(cat.getName());
            //Attr信息
            skuEsModel.setAttrs(attrs);

            //是否有货
            Long skuId = sku.getSkuId();
            try {
                skuEsModel.setHasStock(wareFeign.hasStock(skuId));
            } catch (Exception exception) {
                exception.printStackTrace();
                log.error("库存系统出错");
                skuEsModel.setHasStock(true);
            }
            //spu
            SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId);
            BeanUtils.copyProperties(spuInfoEntity,skuEsModel);
            //salecount
            skuEsModel.setSaleCount(new BigDecimal(0));
            skuEsModel.setHotScore(new BigDecimal(0));
            skuEsModels.add(skuEsModel);
            //System.out.println(skuEsModel);
        }
        R r = searchFeign.upSkuProducts(skuEsModels);
        if (r.getCode()==0){
            //TODO 改变spu修改spu状态
            this.updateSpuStatus(spuId, ProductConstants.UpStatusEnum.Up_SPU_Up.code);
        }else {
            log.error("上传发生问题");

        }


    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);

        return spuInfoEntity;
    }

    private void updateSpuStatus(Long spuId, Integer code) {
        baseMapper.updateSpuStatus(spuId,code);
    }
}





